//
//  MapViewController.m
//  Lightthings
//
//  Created by 王岩 on 2024/12/21.
//

#import "MapViewController.h"
#import <MAMapKit/MAMapKit.h>
#import <AMapFoundationKit/AMapFoundationKit.h>
#import "MASmoothPathTool.h"
#import "GPSDataManager.h"
@interface MapViewController ()<MAMapViewDelegate>

@property (nonatomic, strong) NSArray<MALonLatPoint*> *origTracePoints;
@property (nonatomic, strong) NSArray<MALonLatPoint*> *smoothedTracePoints;

@property (nonatomic, strong) MAMapView *mapView;
@property (nonatomic, strong) MAPolyline *origTrace;
@property (nonatomic, strong) MAPolyline *smoothedTrace;

@property (nonatomic, strong) UISwitch *origTraceSwitch;
@property (nonatomic, strong) UISwitch *smoothedTraceSwitch;

@end

@implementation MapViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [MAMapView updatePrivacyShow:AMapPrivacyShowStatusDidShow privacyInfo:AMapPrivacyInfoStatusDidContain];
    [MAMapView updatePrivacyAgree:AMapPrivacyAgreeStatusDidAgree];

    self.jy_title = SWString(@"运动轨迹");
  

    ///地图需要v4.5.0及以上版本才必须要打开此选项（v4.5.0以下版本，需要手动配置info.plist）
    [AMapServices sharedServices].enableHTTPS = YES;
      ///初始化地图
    MAMapView *_mapView = [[MAMapView alloc] initWithFrame:CGRectMake(0, self.jy_bar_h, kScreenWidth, kScreenHeight - self.jy_bar_h)];
    ///如果您需要进入地图就显示定位小蓝点，则需要下面两行代码
//    _mapView.showsUserLocation = YES;
//    _mapView.userTrackingMode = MAUserTrackingModeFollow;
    [self.view addSubview:_mapView];
    self.mapView = _mapView;
    self.mapView.delegate = self;
    
    self.origTraceSwitch = [[UISwitch alloc] init];
    self.origTraceSwitch.accessibilityIdentifier = @"origTraceSwitch";
    self.smoothedTraceSwitch = [[UISwitch alloc] init];
    self.smoothedTraceSwitch.accessibilityIdentifier = @"smoothedTraceSwitch";
    
    self.origTraceSwitch.center = CGPointMake(15 + self.origTraceSwitch.bounds.size.width / 2, self.view.bounds.size.height - 90);
    self.smoothedTraceSwitch.center = CGPointMake(self.origTraceSwitch.center.x, self.origTraceSwitch.center.y + self.origTraceSwitch.bounds.size.height + 5);
    
    UILabel *label1 = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(self.origTraceSwitch.frame) + 5, self.origTraceSwitch.frame.origin.y, 100, CGRectGetHeight(self.origTraceSwitch.bounds))];
    label1.text = @"原始轨迹";
    UILabel *label2 = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(self.smoothedTraceSwitch.frame) + 5, self.smoothedTraceSwitch.frame.origin.y, 100, CGRectGetHeight(self.smoothedTraceSwitch.bounds))];
    label2.text = @"平滑轨迹";
    
    [self.view addSubview:label1];
    [self.view addSubview:self.origTraceSwitch];
    [self.view addSubview:label2];
    [self.view addSubview:self.smoothedTraceSwitch];
    
    //
    [self.origTraceSwitch addTarget:self action:@selector(onOrig:) forControlEvents:UIControlEventValueChanged];
    [self.smoothedTraceSwitch addTarget:self action:@selector(onSmoothed:) forControlEvents:UIControlEventValueChanged];
    
    [self.origTraceSwitch setOn:YES];
    
    [self initPolylines];
    
    [self.mapView removeOverlay:self.origTrace];
    [self.mapView addOverlay:self.origTrace];
    
    
    NSString * uuid = self.metaInfo[@"uuid"];
    NSArray * list = [FRQBluetoothManager shareManager].curPeripherals;
    for (CBPeripheral * per in list) {
        if ([per.identifier.UUIDString isEqualToString:uuid]) {
            self.peripheral = per;
            [self readData];
        }
    }
    // Do any additional setup after loading the view.
}
- (void)initPolylines {
    
    if ([GPSDataManager.sharedInstance getAllGPSData].count == 0) {
        return;
    }
    
    
    [self loadTracePoints];
    
    if(self.origTracePoints.count == 0) {
        _mapView.showsUserLocation = YES;
        return;
    }
    
    [self initOriginalTrace];
    
    [self initSmoothedTrace];
}

- (void)initOriginalTrace {
    CLLocationCoordinate2D *pCoords = malloc(sizeof(CLLocationCoordinate2D) * self.origTracePoints.count);
    if(!pCoords) {
        return;
    }
    
    for(int i = 0; i < self.origTracePoints.count; ++i) {
        MALonLatPoint *p = [self.origTracePoints objectAtIndex:i];
        CLLocationCoordinate2D *pCur = pCoords + i;
        pCur->latitude = p.lat;
        pCur->longitude = p.lon;
    }
    
    self.origTrace = [MAPolyline polylineWithCoordinates:pCoords count:self.origTracePoints.count];
    if(pCoords) {
        free(pCoords);
    }
}

- (void)initSmoothedTrace {
    MASmoothPathTool *tool = [[MASmoothPathTool alloc] init];
    tool.intensity = 3;
    tool.threshHold = 0.3;
    tool.noiseThreshhold = 10;
    self.smoothedTracePoints = [tool pathOptimize:self.origTracePoints];
    
    CLLocationCoordinate2D *pCoords = malloc(sizeof(CLLocationCoordinate2D) * self.smoothedTracePoints.count);
    if(!pCoords) {
        return;
    }

    for(int i = 0; i < self.smoothedTracePoints.count; ++i) {
        MALonLatPoint *p = [self.smoothedTracePoints objectAtIndex:i];
        CLLocationCoordinate2D *pCur = pCoords + i;
        pCur->latitude = p.lat;
        pCur->longitude = p.lon;
    }

    self.smoothedTrace = [MAPolyline polylineWithCoordinates:pCoords count:self.smoothedTracePoints.count];
    if(pCoords) {
        free(pCoords);
    }
}

- (void)loadTracePoints {
    NSString *filePath = [NSString stringWithFormat:@"%@/AMapTrace2.txt", [[NSBundle mainBundle] bundlePath]];
    NSData *fileData = [NSData dataWithContentsOfFile:filePath];
    NSString *str = [[NSString alloc] initWithData:fileData encoding:NSUTF8StringEncoding];
    NSArray *arr = [str componentsSeparatedByString:@"\n"];
    NSMutableArray *results = [NSMutableArray array];
//    for(NSString *oneLine in arr) {
//        NSArray *items = [oneLine componentsSeparatedByString:@","];
//        
//        if(items.count == 3) {
//            NSString *lat = [items objectAtIndex:1];
//            NSString *lon = [items objectAtIndex:2];
//            MALonLatPoint *point = [[MALonLatPoint alloc] init];
//            point.lat = [lat doubleValue];
//            point.lon = [lon doubleValue];
//            [results addObject:point];
//        }
//    }
    arr = [GPSDataManager.sharedInstance getAllGPSData];
    //  处理 GPS数据
    for ( int i = 0 ; i < arr.count; i ++) {
        
        MALonLatPoint *point = [[MALonLatPoint alloc] init];
        
        //  00000000 0a 00 06c562dc 0155892e
        NSString * valueStr = [arr[i] substringWithRange:NSMakeRange(12, 2)];
        unsigned long value = strtoll([[NSString stringWithFormat:@"0x%@",valueStr] UTF8String], 0, 16);
//        if ((value & 0x80) == 0x80) {
//            value = value & 0x7f;
//        }

        valueStr = [arr[i] substringWithRange:NSMakeRange(12, 8)];
        value = strtoll([[NSString stringWithFormat:@"0x%@",valueStr] UTF8String], 0, 16);
        NSLog(@"精度：%lu",value);
        point.lon = value * 0.000001;

        valueStr = [arr[i] substringWithRange:NSMakeRange(20, 8)];
        value = strtoll([[NSString stringWithFormat:@"0x%@",valueStr] UTF8String], 0, 16);
        NSLog(@"纬度：%lu",value);
        point.lat = value * 0.000001;

        [results addObject:point];

    }
    self.origTracePoints = results;
}

- (void)onOrig:(UISwitch *)sender
{
    if(sender.isOn) {
        if([self.mapView.overlays containsObject:self.smoothedTrace]) {
            [self.mapView insertOverlay:self.origTrace belowOverlay:self.smoothedTrace];
        } else {
            [self.mapView addOverlay:self.origTrace];
        }
    } else {
        [self.mapView removeOverlay:self.origTrace];
    }
}

- (void)onSmoothed:(UISwitch *)sender
{
    if(sender.isOn) {
        [self.mapView addOverlay:self.smoothedTrace];
    } else {
        [self.mapView removeOverlay:self.smoothedTrace];
    }
}

#pragma <MAMapViewDelegate>
- (MAOverlayRenderer *)mapView:(MAMapView *)mapView rendererForOverlay:(id <MAOverlay>)overlay
{
    if (overlay == self.origTrace)
    {
        MAPolylineRenderer * polylineRenderer = [[MAPolylineRenderer alloc] initWithPolyline:self.origTrace];
        
        polylineRenderer.lineWidth = 4.f;
        polylineRenderer.strokeColor = [UIColor greenColor];
        
        return polylineRenderer;
        
    } else if (overlay == self.smoothedTrace) {
        MAPolylineRenderer * polylineRenderer = [[MAPolylineRenderer alloc] initWithPolyline:self.smoothedTrace];
        
        polylineRenderer.lineWidth = 4.f;
        polylineRenderer.strokeColor = [UIColor colorWithRed:1.0 green:(int)0xc1/255.0 blue:0x25/255.0 alpha:1.0];
        
        return polylineRenderer;
        
    }
    
    return nil;
}

- (void)readData {
    [WatchCommandTool.sharedInstance writeStormCommand:Command_GPSData ToPeripheral:self.peripheral Value:nil reBack:^(NSString * _Nonnull backData) {
        if (backData.length) {
            [self initPolylines];
            [self.mapView showOverlays:@[self.origTrace] animated:NO];

            
            //  54590101aa033a0011030a000d 00000000 0a 06c562dc 0155892e
            NSString * valueStr = [backData substringWithRange:NSMakeRange(36, 2)];
            unsigned long value = strtoll([[NSString stringWithFormat:@"0x%@",valueStr] UTF8String], 0, 16);
            if ((value & 0x80) == 0x80) {
                value = value & 0x7f;
            }

            valueStr = [backData substringWithRange:NSMakeRange(36, 8)];
            value = strtoll([[NSString stringWithFormat:@"0x%@",valueStr] UTF8String], 0, 16);
            NSLog(@"精度：%lu",value);
            valueStr = [backData substringWithRange:NSMakeRange(44, 8)];
            value = strtoll([[NSString stringWithFormat:@"0x%@",valueStr] UTF8String], 0, 16);
            NSLog(@"纬度：%lu",value);
        }
    }];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
